import { _decorator, Collider2D, Component, Node, UITransform, Vec2 } from 'cc';
import { Unit } from './Unit';
import { UnitSpacecraftBase } from './UnitSpacecraftBase';
import { UnitAsteroid } from './UnitAsteroid';
import { EconomicCom } from './Component/EconomicCom';
import { UnitPlanet } from './UnitPlanet';
import { UnitType } from '../Util/Global';
const { ccclass, property } = _decorator;

@ccclass('UnitMining')
export class UnitMining extends UnitSpacecraftBase {

    /**工作效率 */
    public working_efficiency: number = 10;
    public parentEconomic: EconomicCom = null;

    protected start(): void {
        super.start();
        this.unitType = UnitType.UnitMining;

        this.arsenal.Reset();

    }
    protected onEnable(): void {
        super.onEnable();
    }

    protected onDisable(): void {
        super.onDisable();
        this._changeCount = 0;
        this.parentEconomic = null;
    }

    private _changeMoveInterval: number = 1;
    private _changeCount: number = 0;

    protected _updateLogic(dt: number) {
        super._updateLogic(dt);
        if (this.parentEconomic == null && this.parentUnit) {
            this.parentEconomic = this.parentUnit.getComponent(EconomicCom);
        }

        if (this._lifeTime > this._changeMoveInterval * this._changeCount) {
            this.ChangeMoveDir();
            this._changeCount++;
        }

        if (this.target && !this.target.death) {
            //当靠近目标后改为环绕
            // this.ChangeChaseTargetDir();
            if (this.DistanceOther(this.target) > 100) {
                this.ChangeChaseTargetDir();
            }
            else {
                this.SurroundTargetDir();
                //开采行星
                let resPlanet = this.target as UnitAsteroid;
                let hasRes = resPlanet.mine_res && (resPlanet.mine_res -= dt * this.working_efficiency);
                if (!hasRes) {
                    this.target = null;
                }
                else {
                    this.parentEconomic && this.parentEconomic.AddMineRes(dt * this.working_efficiency);
                }
            }

        }
        else if (!this.TooFarFromParent()) {
            this.target = this.FindTargetWeightAndNearest();
            if (!this.target || this.target.death) { //从父级获取目标
                if (this.parentUnit) {
                    let parentPlanet = this.parentUnit as UnitPlanet;
                    this.target = parentPlanet.FindOneSatellite(UnitType.UnitAsteroid);
                    if (!this.target) {//找引力范围的
                        parentPlanet.FilterSelfImpactPlanet_One((planet) => {
                            if (planet.unitType == UnitType.UnitAsteroid) {
                                this.target = planet;
                                return true;
                            }
                        })
                    }
                }
            }
        }

        this.AutoMove();
    }

    protected addParentEnemy(unit: Unit) {
        if (this.parentUnit && !this.parentUnit.death) {
            this.parentUnit.AddEnemy(unit);
        }
    }

    protected lostParentEnemy(unit: Unit) {
        if (this.parentUnit && !this.parentUnit.death) {
            this.parentUnit.LostEnemy(unit);
        }
    }

    protected onTriggerEnter(selfCollider: Collider2D, otherCollider: Collider2D) {
        super.onTriggerEnter(selfCollider, otherCollider);
        // 只在两个碰撞体开始接触时被调用一次
        let other = otherCollider.node.getComponent(Unit);

        if (other && other != this.parentUnit) {//对方不是自己父级
            if (other.unitType == UnitType.UnitAsteroid) {
                this.AddTarget(other);

                this.target = this.FindTargetWeightAndNearest(other);
            }
            else if (other.unitType == UnitType.UnitPlanet) {
                this.addParentEnemy(other);
            }
            else if (other instanceof UnitSpacecraftBase) {
                this.addParentEnemy(other);
            }
        }
    }

    protected onTriggerExit(selfCollider: Collider2D, otherCollider: Collider2D) {
        super.onTriggerExit(selfCollider, otherCollider);
        let other = otherCollider.node.getComponent(Unit);

        if (other && other != this.parentUnit) {
            if (other.unitType == UnitType.UnitAsteroid) {
                this.LostTarget(other);
            }
            else if (other.unitType == UnitType.UnitPlanet) {
                this.lostParentEnemy(other);
            }
            else if (other instanceof UnitSpacecraftBase) {
                this.lostParentEnemy(other);
            }
        }
    }

    /**选择序列大的、或者距离近的目标优先 */
    FindTargetWeightAndNearest(newEnemy?: Unit): Unit {
        let tempDis = 0;

        if (newEnemy && this.target && !this.target.death) {//检测是否需要更换目标
            tempDis = this.DistanceOther(this.target);
            if (this.target.unitType > newEnemy.unitType || tempDis < this.DistanceOther(newEnemy)) {
                return this.target;
            }
            else {
                return newEnemy;
            }
        }

        let weightOrNearestUnit = null;
        let unValidUnits: Unit[] = [];//无效目标
        for (let kv of this.targetList) {
            if (!kv[0].death && kv[0] instanceof UnitAsteroid) {
                let dis = this.DistanceOther(kv[0]);
                if ((weightOrNearestUnit && weightOrNearestUnit.unitType < kv[0].unitType)
                    || tempDis == 0
                    || dis < tempDis) {

                    tempDis = dis;
                    weightOrNearestUnit = kv[0];
                }
            }
            else {
                unValidUnits.push(kv[0]);
            }
        }

        for (let i = 0; i < unValidUnits.length; i++) {
            this.targetList.delete(unValidUnits[i]);
            if (weightOrNearestUnit == null && newEnemy && unValidUnits[i] == newEnemy) {
                if (newEnemy.destructable) {
                    if (newEnemy.destructable.next_remain_hp > 0) {
                        // console.log('警告==>新可存活目标但被忽略！！？', newEnemy.destructable.next_remain_hp);
                    }
                    else if (newEnemy.hp <= 0) {

                        console.log('警告==>新目标已死亡怎么没销毁！！？', newEnemy.hp);
                    }
                    unValidUnits[i].death;
                }
            }
        }

        return weightOrNearestUnit;
    }
}


